<template>
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <!-- 一般性的list底部弹出框 -->
    <view class="popup-content">
      <view v-if="!!props.singleSelect" class="popup-header">
        <text class="popup-title">{{ props.title }}</text>
        <text class="popup-close" @click="close">×</text>
      </view>

      <!-- 标题栏 -->
      <view v-if="!!!props.singleSelect" class="popup-header-box">
        <view class="popup-header-left">
          <text class="btn-cancel" @click="close">取消</text>
        </view>
        <view class="popup-header-center">{{ props.title }}</view>
        <view class="popup-header-right">
          <text
            class="btn-confirm"
            :class="{ 'hide-confirm': props.singleSelect }"
            @click="confirmClick"
            >确定</text
          >
        </view>
      </view>

      <!-- 搜索区域 -->
      <view class="search-wrapper">
        <up-input
          v-model="info.spell"
          placeholder="请输入"
          clearable
          @change="filterContent"
          class="h-full"
        ></up-input>
      </view>

      <scroll-view
        class="popup-body"
        scroll-y
        @scrolltolower="loadMore"
        @scrolltoupper="refreshContent"
      >
        <view class="tree-list">
          <view
            v-for="group in filteredList"
            :key="group.id"
            class="tree-group"
          >
            <!-- 一级菜单 -->
            <view class="group-title" @click="toggleGroup(group)">
              <text class="expand-icon">{{
                group.isExpanded ? '▼' : '▶'
              }}</text>
              <text>{{ group.name }}</text>
            </view>

            <!-- 二级菜单 -->
            <view v-if="group.isExpanded" class="children-wrap">
              <view
                v-for="child in filterChildren(group.children)"
                :key="child.id"
                :class="[
                  'child-item',
                  { 'line-select': info.select.includes(child.id) },
                ]"
                @click="handleSelect(child)"
              >
                <!-- 多选模式下显示勾选框 -->
                <text v-if="!props.singleSelect" class="checkbox">
                  {{ isSelected(child.id) ? '☑' : '☐' }}
                </text>
                <text>{{ child.name }}</text>
              </view>
            </view>
          </view>
        </view>

        <up-empty v-show="info.list.length === 0" mode="search"></up-empty>
      </scroll-view>
    </view>
  </uni-popup>
</template>

<script setup>
import { watch } from 'vue';
import utils from '@/common/js/utils/index.js';
import {
  getDict, // 获取数据字典
} from '@/api';

const popup = ref(null);

const props = defineProps({
  title: {
    type: String,
    default: '选择',
  },
  // 数据字典查询的key
  categoryType: {
    type: String,
    default: '',
    required: true,
  },
  // 父组件中对应的字段
  submitKey: {
    type: String,
    default: '',
    required: true,
  },
  // 是否单选
  singleSelect: {
    type: [Boolean, null],
    default: true,
  },
  // 默认选择项
  defaultSelected: {
    type: [Array, String],
    default: '',
  },
});

const info = reactive({
  spell: '', // 顶部查询
  list: [], // 数据列表--供渲染层级
  data: [], // 数据列表--供筛选使用
  select: [], // 选择项
});

watch(
  () => props.defaultSelected,
  (newVal) => {
    if (typeof newVal === 'string') {
      info.select = newVal === '' ? [] : [newVal];
    } else if ([null, undefined].includes(newVal)) {
      info.select = [];
    } else {
      info.select = newVal;
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

const open = () => popup.value.open('bottom');
const close = () => popup.value.close();

const emit = defineEmits(['select', 'update:modelValue']);

// const select = (item) => {
//   emit('select', item, props.submitKey);
//   close();
// };

/* 获取数据字典的值 */
const getDictData = () => {
  info.list = [];
  info.data = [];
  getDict({
    categoryType: props.categoryType,
  })
    .then((res) => {
      if (res) {
        info.data = res || [];
        turnDictData(res || []);
      }
    })
    .catch((err) => {
      console.log(`${dict_key} err`, err);
    });
};
// 转换树形数据字典
const turnDictData = (data) => {
  if (!data.length) {
    info.list = [];
    return false;
  }

  let group_id = 1;
  // 使用 Map 来存储分组数据
  const groupMap = new Map();

  // 第一次遍历，按 groups 分组
  data.forEach((item) => {
    if (!groupMap.has(item.groups)) {
      groupMap.set(item.groups, {
        id: 'group' + group_id++,
        name: item.groups,
        children: [],
      });
    }

    // 添加子项
    groupMap.get(item.groups).children.push({
      id: item.value,
      name: item.showname || '',
      value: item.value || '',
    });
  });

  // 转换 Map 为数组
  info.list = Array.from(groupMap.values());
  console.log('info.list', info.list);
};

/*
{
    "showname": "ZP01-保养维护工单",
    "category_code": "order_type_dict",
    "name": "保养维护工单",
    "groups": "预防性保养",
    "value": "ZP01"
  },
*/

// 存储展开状态
const expandedGroups = ref(new Set());

// 切换组展开状态
const toggleGroup = (group) => {
  if (expandedGroups.value.has(group.id)) {
    expandedGroups.value.delete(group.id);
  } else {
    expandedGroups.value.add(group.id);
  }
};

// 过滤和处理列表数据
const filteredList = computed(() => {
  let filteredData = info.list;

  // 如果有搜索内容，对数据进行过滤
  if (info.spell) {
    filteredData = info.list
      .map((group) => {
        // 过滤符合条件的子项
        const filteredChildren = group.children.filter((child) =>
          child.name.toLowerCase().includes(info.spell.toLowerCase())
        );

        // 如果有匹配的子项，则保留该组并自动展开
        if (filteredChildren.length > 0) {
          expandedGroups.value.add(group.id);
          return {
            ...group,
            children: filteredChildren,
            isExpanded: true,
          };
        }
        return null;
      })
      .filter(Boolean); // 移除空值
  }

  // 添加展开状态
  const end_arr = filteredData.map((group) => ({
    ...group,
    isExpanded: expandedGroups.value.has(group.id),
  }));
  console.log('261最终展示end_arr', end_arr);
  return end_arr;
});

// 搜索处理函数
const filterContent = utils.debounce((val) => {
  info.spell = val;
}, 300);

// 过滤子项
const filterChildren = (children) => {
  if (!info.spell) return children;
  return children.filter((child) =>
    child.name.toLowerCase().includes(info.spell.toLowerCase())
  );
};

// 选择处理
const handleSelect = (child) => {
  if (props.singleSelect) {
    // 单选模式
    info.select = [child.id];
    confirmClick();
  } else {
    // 多选模式
    const index = info.select.indexOf(child.id);
    if (index > -1) {
      // 如果已选中，则取消选中
      info.select.splice(index, 1);
    } else {
      // 如果未选中，则添加选中
      info.select.push(child.id);
    }
  }
};

// 可以添加一个检查选中状态的方法
const isSelected = (childId) => {
  return info.select.includes(childId);
};

// 右上角确定按钮事件
const confirmClick = () => {
  let len = info.data.length;
  const name_arr = [];
  info.select.forEach((item_1) => {
    for (let i = 0; i < len; i++) {
      const item_2 = info.data[i];
      if (item_1 === item_2.value) {
        name_arr.push(item_2.name);
      }
    }
  });
  emit(
    'select',
    {
      name: name_arr,
      value: info.select,
    },
    props.submitKey
  );
  popup.value.close();
};

onMounted(() => {
  getDictData();
});

defineExpose({
  open,
  close,
});
</script>

<style lang="scss" scoped>
.popup-content {
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 20rpx 10rpx 15rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-header-box {
  display: flex;
  height: 40px;
  padding: 0 10rpx;
  align-items: center;

  .popup-header-left {
    .btn-cancel {
      display: inline-flex;
      padding: 6px;
      color: #999;
      font-size: 22px;
    }
  }

  .popup-header-center {
    width: 60%;
    flex: 1;
    text-align: center;
    font-size: 22px;
    font-weight: bold;
  }

  .popup-header-right {
    .btn-confirm {
      display: inline-flex;
      padding: 6px;
      color: #333;
      font-size: 20px;

      &.hide-confirm {
        visibility: hidden;
        pointer-events: none;
      }
    }
  }
}

.popup-title {
  font-size: 24rpx;
  font-weight: bold;
}

.popup-close {
  font-size: 35rpx;
  color: #999;
}

.search-wrapper {
  margin: 10px 0 10px 0;
  padding: 0 12px;
  height: 34px;
}

.popup-body {
  max-height: 55vh;
  min-height: 55vh;

  .popup-item {
    padding: 14rpx 20rpx;
    border-top: 1rpx solid #e5e5e5;

    &:last-child {
      border-bottom: 1rpx solid #e5e5e5;
    }

    &.active {
      color: #f00;
    }
  }
}

.tree-list {
  .tree-group {
    margin-bottom: 10rpx;

    .group-title {
      display: flex;
      align-items: center;
      padding: 20rpx;
      background-color: #f5f5f5;

      .expand-icon {
        margin-right: 20rpx;
        font-size: 24rpx;
      }
    }

    .children-wrap {
      padding-left: 60rpx;
      display: flex;
      flex-wrap: wrap;

      .child-item {
        padding: 16rpx 20rpx;
        margin: 10rpx;
        background-color: #ffffff;
        border-radius: 6rpx;
        font-size: 28rpx;

        display: flex;
        align-items: center;

        .checkbox {
          margin-right: 10rpx;
          font-size: 32rpx;
        }

        &.line-select {
          background-color: #e6f7ff;
          color: #1890ff;
        }
      }
    }
  }
}
</style>
